import { FC, useEffect, useState, useRef } from "react";
import { observer, inject } from "mobx-react";
import { Select, Input, Modal, Space, Row, Col, Button, Form } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import _ from "lodash";
import { ITStore } from "../../store";

interface TProp {
  store: ITStore;
}

interface ITRMProp extends TProp {
  close: () => void;
}

const ReagentSlotModal: FC<ITRMProp | any> = ({
  store,
  close,
}: ITRMProp): JSX.Element => {
  const {
    languageStore: { lang },
    reagentStore: {
      getReagentTitle,
      searchReagent,
      searchUserReagent,
      searchLoading,
      changeShowAddEditModal,
    },
    designerStore: {
      addReagents,
      updateReagents,
      removeReagent,
      showReagentAddEditModal,
      reagentAddEditData,
      currentDesigner,
      addEditReagentLoading,
    },
    userStore: { getUserInfo },
  } = store;
  const [form] = Form.useForm();
  const { slotName, bottleName, reagent } = reagentAddEditData || {};

  const [options, setOptions] = useState<any>([]);

  // 试剂类型 0：未知  1：液体 2：固体
  const [reagentType, setReagentType] = useState<number>(0);

  const [searchText, setSearchText] = useState("");
  const fetchIdRef = useRef(0);
  const abortControllerRef = useRef<AbortController>();

  // 匹配度评分函数
  const getMatchScore = (item: any, keyword: string) => {
    const lowerKeyword = keyword.toLowerCase();
    let score = 0;

    const matchFields = [
      { key: "name", weight: 5 },
      { key: "abbreviation", weight: 4 },
      { key: "formula", weight: 3 },
      { key: "casno", weight: 2 },
      { key: "cnname", weight: 1 },
    ];

    matchFields.forEach(({ key, weight }) => {
      const value = String(item[key] || "").toLowerCase();
      const position = value.indexOf(lowerKeyword);
      if (position !== -1) {
        score += (100 - Math.min(position, 99)) * weight;
      }
    });

    return score;
  };

  // 高亮组件
  const HighlightText = ({
    text,
    keyword,
  }: {
    text: string;
    keyword: string;
  }) => {
    if (!text || !keyword) return <>{text}</>;

    const regex = new RegExp(`(${_.escapeRegExp(keyword)})`, "gi");
    const parts = text.split(regex);

    return (
      <span>
        {parts.map((part, i) =>
          regex.test(part) ? (
            <span key={i} className="highlight">
              {part}
            </span>
          ) : (
            part
          )
        )}
      </span>
    );
  };

  // 搜索处理
  const onSearch = async (keyword: string) => {
    try {
      const fetchId = ++fetchIdRef.current;
      setSearchText(keyword);

      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      abortControllerRef.current = new AbortController();

      if (keyword.length >= 2) {
        const userInfo = getUserInfo();
        // 先搜索用户试剂，再搜索公共试剂库
        const userResult = await searchUserReagent({
          keyword,
          user: userInfo.id,
        });

        // 排序逻辑
        const sortedUserResults = _.orderBy(
          userResult,
          [(item) => getMatchScore(item, keyword)],
          ["desc"]
        );

        const userResultOptions = sortedUserResults.map((item) => ({
          label: (
            <div>
              <HighlightText text={item.name} keyword={keyword}/>
              {item.abbreviation && (
                <>
                  (<HighlightText text={item.abbreviation} keyword={keyword} />)
                </>
              )}

              {item.casno && (
                <span style={{ marginLeft: 8 }}>
                  (<HighlightText text={item.casno} keyword={keyword} />)
                </span>
              )}

              {item.formula && (
                <span style={{ marginLeft: 8 }}>
                  <HighlightText text={item.formula} keyword={keyword} />
                </span>
              )}
              {item.cnname && (
                <div style={{ color: "#888", fontSize: 12 }}>
                  <HighlightText text={item.cnname} keyword={keyword} />
                </div>
              )}
            </div>
          ),
          value: item.id,
          display: `${item.name}${
            item.abbreviation ? `(${item.abbreviation})` : ""
          }`, // 新增display字段
          data: item,
        }));

        const result = await searchReagent({
          keyword,
          signal: abortControllerRef.current.signal,
        });

        if (fetchId !== fetchIdRef.current) return;

        // 排序逻辑
        const sortedResults = _.orderBy(
          result,
          [(item) => getMatchScore(item, keyword)],
          ["desc"]
        );

        // 修改后的options生成逻辑
        const resultOptions = sortedResults.map((item) => ({
          label: (
            <div>
              <HighlightText text={item.name} keyword={keyword} />
              {item.abbreviation && (
                <>
                  (<HighlightText text={item.abbreviation} keyword={keyword} />)
                </>
              )}
              {item.formula && (
                <span style={{ marginLeft: 8 }}>
                  <HighlightText text={item.formula} keyword={keyword} />
                </span>
              )}
              {item.cnname && (
                <span style={{ color: "#888", paddingLeft: 4 }}>
                  <HighlightText text={item.cnname} keyword={keyword} />
                </span>
              )}
              {item.casno && (
                <span style={{ color: "#888", paddingLeft: 4 }}>
                  (<HighlightText text={item.casno} keyword={keyword} />)
                </span>
              )}
            </div>
          ),
          value: item.id,
          display: `${item.name}${
            item.abbreviation ? `(${item.abbreviation})` : ""
          }`, // 新增display字段
          data: item,
        }));

        setOptions([...userResultOptions, ...resultOptions]);
      }
    } catch (error: any) {
      if (error.name !== "AbortError") {
        console.error("Search error:", error);
      }
    }
  };

  const debounceSearch = _.debounce(onSearch, 400);

  const clearReagent = async () => {
    if (currentDesigner) {
      let { id } = currentDesigner;
      const { slotName, bottleName } = reagentAddEditData;
      await removeReagent({ slotName, bottleName, designerId: id });
      closeModal();
    }
  };

  const onFinish = async (data: any) => {
    const { reagentId } = data;
    let param: any = {};
    param.type = reagentType;
    param.reagentId = reagentId;
    let { id } = currentDesigner as any;
    if (!reagent) {
      // 新增
      await addReagents({
        designerId: id,
        data: param,
        slotName,
        bottleName,
      });
    } else {
      // 编辑
      await updateReagents({
        designerId: id,
        data,
        slotName,
        bottleName,
      });
    }

    closeModal();
  };

  const closeModal = () => {
    //   setAddonAfter("");
    //   setAmountTitle(lang["langamount"]);
    form.resetFields();
    setOptions([]);

    //   setMmolWeightVolume("");
    close();
  };

  // 组件卸载清理
  useEffect(() => {
    return () => {
      abortControllerRef.current?.abort();
      debounceSearch.cancel();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 新增初始化逻辑
  useEffect(() => {
    if (reagent && form) {
      const { reagentId } = reagent;
      const tempReagentInf = getReagentTitle(reagentId, lang);
      setReagentType(tempReagentInf.type);
      form.setFieldsValue({
        reagentId: reagent.id,
        displayText: `${reagent.name}${
          reagent.abbreviation ? `(${reagent.abbreviation})` : ""
        }`,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [reagent]);

  return (
    <Modal
      title={
        <Row>
          <Col span={12}>
            <Space>
              {bottleName}
              {lang["langchoosereagent"]}
            </Space>
          </Col>
          <Col span={11}>
            <Space style={{ float: "right" }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  changeShowAddEditModal(true);
                }}
              >
                {lang["langaddreagent"]}
              </Button>
            </Space>
          </Col>
          <Col span={1}></Col>
        </Row>
      }
      open={showReagentAddEditModal}
      onCancel={closeModal}
      destroyOnClose={true}
      confirmLoading={addEditReagentLoading}
      width={780}
      footer={
        <Row>
          <Col span={2}>
            <Button
              type="primary"
              danger
              onClick={() => {
                clearReagent();
              }}
              // disabled={displayClear}
            >
              {lang["langclear"]}
            </Button>
          </Col>
          <Col span={22}>
            <Space>
              <Button onClick={closeModal}>{lang["langclose"]}</Button>
              <Button
                type="primary"
                onClick={() => {
                  form.submit();
                }}
              >
                {lang["langok"]}
              </Button>
            </Space>
          </Col>
        </Row>
      }
    >
      <Form
        name="reaginetForm"
        form={form}
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 21 }}
        onFinish={onFinish}
        initialValues={{ displayText: "" }}
      >
        {/* 隐藏字段保存显示文本 */}
        <Form.Item hidden name="displayText">
          <Input />
        </Form.Item>
        <Form.Item
          label={lang["langreagent"]}
          name="reagentId"
          rules={[{ required: true }]}
        >
          <Select
            showSearch
            filterOption={false}
            onSearch={debounceSearch}
            loading={searchLoading}
            options={options}
            notFoundContent={null}
            // dropdownRender={(menu) => (
            //   <div style={{ minHeight: 600, overflow: "auto" }}>{menu}</div>
            // )}
            filterSort={(a, b) => {
              // 本地二次排序
              const keyword = searchText.toLowerCase();
              return (
                getMatchScore(b.data, keyword) - getMatchScore(a.data, keyword)
              );
            }}
            optionLabelProp="display"
            onChange={(value) => {
              // 更新显示文本
              const selectedOption = options.find(
                (opt: any) => opt.value === value
              );
              form.setFieldsValue({
                reagentId: value,
                displayText: selectedOption?.display,
              });
            }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default inject("store")(observer(ReagentSlotModal));
